package pl.com.sthaether.mc.event.file;

import javafx.embed.swing.SwingFXUtils;
import javafx.scene.SnapshotParameters;
import javafx.scene.image.WritableImage;
import pl.com.sthaether.mc.event.MCEventType;
import pl.com.sthaether.mc.event.MCParallelEvent;
import pl.com.sthaether.mc.main.MCMainPane;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;

public class MCExportImageEvent extends MCParallelEvent {


    public MCExportImageEvent(String actionName, MCEventType type, boolean registerOnBus) {
        super(actionName, type, registerOnBus);
    }

    @Override
    protected Void eventSteps() {
        File file = prepareFile();
        WritableImage snapshot = MCMainPane.getInstance().getWorkspacePane().snapshot(new SnapshotParameters(), null);//TODO make sure that you want pl.com.sthaether.mc.graphics from whole panel - maybe extract some inner method to do that
        BufferedImage bufferedImage = new BufferedImage((int) MCMainPane.getInstance().getWorkspacePane().getWidth(), (int) MCMainPane.getInstance().getWorkspacePane().getHeight(), BufferedImage.TYPE_INT_ARGB);
        saveImage(snapshot, bufferedImage, file);

        //TODO
        return null;
    }

    private File prepareFile() {
        File file = new File(System.getProperty("user.home") + "/[MC]Mapper/screens/Screen.jpeg");//TODO use filechooser here
        //TODO ask if someone would like to use some extra graphic elements

        if (file.exists()) {
            file.delete();//TODO ask to delete if duplicate
        } else {
            file.getParentFile().mkdirs();
            try {
                file.createNewFile();
            } catch (Exception e) {//TODO handle exception inside
                e.printStackTrace();
            }
        }
        return file;
    }

    private void saveImage(WritableImage snapshot, BufferedImage bufferedImage, File file) {
        BufferedImage image;
        image = SwingFXUtils.fromFXImage(snapshot, bufferedImage);
        try {
            Graphics2D gd = (Graphics2D) image.getGraphics();
            gd.translate(MCMainPane.getInstance().getWorkspacePane().getWidth(), MCMainPane.getInstance().getWorkspacePane().getHeight());
            ImageIO.write(image, "png", file);
        } catch (Exception ex) {
            //TODO handle exception inside? maybe expand it and handle by app exception holder - this place coud suit
        }
        ;
    }
}
